//
//  DevicesViewController.m
//  EquesCat
//
//  Created by Chun Hung Cheung on 2024/12/17.
//

#import "DevicesViewController.h"
#import "ListCollectionViewCell.h"
#import "FBDevicesList.h"
#import "SelectDeviceVController.h"
#import "CatVideoVController.h"

// 蓝牙发现设备
#import <CoreBluetooth/CoreBluetooth.h>
#import "ESPPeripheral.h"
#import "ESPFBYBLEHelper.h"
#import "ESPDataConversion.h"
#import "BluSearchVController.h"

#import "VL4BLUViewController.h"
#import "YKVL0MainViewController.h"

@interface DevicesViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property(nonatomic,strong)UICollectionView *list_collectionview;
@property(nonatomic,strong)NSMutableArray *collectionViewModelArray;
@property(nonatomic,strong)UIImageView *backgroundImageView;
@property(nonatomic,strong)UIButton *addButton;


// 蓝牙发现设备
/*蓝牙定时器*/
@property (nonatomic,strong)dispatch_source_t blu_timer;
// 蓝牙模块
@property(nonatomic, copy) NSMutableArray<ESPPeripheral *> *peripheralArray;
@property(nonatomic, strong)ESPFBYBLEHelper *espFBYBleHelper;
@property(nonatomic, copy) NSString *filterContent;
@property (nonatomic,strong)ESPPeripheral *search_device;
@property (nonatomic,strong)UIAlertController *alertController;


@end

@implementation DevicesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor = [UIColor whiteColor];
     self.title = @"设备列表";
     self.backgroundImageView.image = [UIImage imageNamed:@"my_device"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData) name:@"reloadList" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData) name:@"devst" object:nil];
    
    
    [self.addButton setImage:[UIImage imageNamed:@"3.0_add_devices"] forState:UIControlStateNormal];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //设置导航栏背景图片为一个空的image，这样就透明了
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    //去掉透明后导航栏下边的黑边
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    
    [UIApplication sharedApplication].statusBarStyle =  UIStatusBarStyleLightContent;
    
    if(@available(iOS 15.0,*)){
      
        UINavigationBarAppearance *barApp = [[UINavigationBarAppearance alloc]init];
        barApp.backgroundColor = [UIColor clearColor];
        barApp.backgroundEffect = nil;
        barApp.shadowColor = nil;
        self.navigationController.navigationBar.scrollEdgeAppearance = nil;
        self.navigationController.navigationBar.standardAppearance = barApp;
    
     }
    
    self.addButton.hidden = NO;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(delete_device) name:@"rmbdy_result" object:nil];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    self.addButton.hidden = YES;
}

- (void)delete_device
{
    [SVProgressHUD dismiss];
    
    [SVProgressHUD showSuccessWithStatus:@"删除设备成功"];
    
}

- (UIButton*)addButton
{
    if (!_addButton) {
         _addButton = [[UIButton alloc]init];
         _addButton.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,-36);
        [_addButton addTarget:self action:@selector(addButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self.navigationController.navigationBar addSubview:_addButton];
         _addButton.frame = CGRectMake(kScreenWidth-74,0,60,self.navigationController.navigationBar.frame.size.height);
    }
    return _addButton;
}

- (void)addButtonClick
{
     SelectDeviceVController *vc = [[SelectDeviceVController alloc]init];
     self.addButton.hidden = YES;
     vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)reloadData
{
    
     NSArray *array = [FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken])]];
     self.collectionViewModelArray = [NSMutableArray arrayWithArray:array];
    
     self.list_collectionview.dataSource = self;
     self.list_collectionview.delegate = self;
    [self.list_collectionview reloadData];
}

- (NSMutableArray*)collectionViewModelArray
{
    if (!_collectionViewModelArray) {
        _collectionViewModelArray = [NSMutableArray array];
    }
    return _collectionViewModelArray;
}

#pragma mark Collectionview
- (UICollectionView*)list_collectionview
{
    if (!_list_collectionview) {
        
        //创建一个流水布局
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake((kScreenWidth-35)/2,80);
        // 设置滚动的方向
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        // 距离屏幕左右间距
        layout.sectionInset = UIEdgeInsetsMake(0, 14, 0, 14);
        
        // 设置cell之间的间距
        layout.minimumInteritemSpacing = 7;
        
         _list_collectionview = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
         _list_collectionview.alwaysBounceVertical = YES;  // 垂直
        [_list_collectionview registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
        [_list_collectionview registerClass:[ListCollectionViewCell class] forCellWithReuseIdentifier:@"MainCellName"];
         _list_collectionview.backgroundColor = [UIColor clearColor];
        UILongPressGestureRecognizer *longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
        longPressGr.minimumPressDuration = 1.0;
        [_list_collectionview addGestureRecognizer:longPressGr];
         _list_collectionview.dataSource = self;
         _list_collectionview.delegate = self;
        [self.view addSubview:_list_collectionview];
        [_list_collectionview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.top.equalTo(self.view.mas_top).offset(100);
            make.bottom.equalTo(self.view.mas_bottom);
        }];
    }
    return _list_collectionview;
}


-(void)longPressToDo:(UILongPressGestureRecognizer *)gesture
{
    
      if(gesture.state != UIGestureRecognizerStateBegan){
           return;
       }
       NSIndexPath *indexPath;

       CGPoint point = [gesture locationInView:self.list_collectionview];
       indexPath = [self.list_collectionview indexPathForItemAtPoint:point];
       if(indexPath == nil){
           return;
       }
        
       NSLog(@"长按某个设备row = %ld",(long)indexPath.row);
       FBDevicesList *list = self.collectionViewModelArray[indexPath.row];
    
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示", nil) message:@"确定删除设备？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [SVProgressHUD show];
            //发送删除命令
            [YKBusinessFramework equesDelDeviceWithBid:list.bid];
        }];
        [alertController addAction:cancelButton];
        [alertController addAction:deleteButton];
        [self presentViewController:alertController animated:YES completion:nil];
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    header.backgroundColor = [UIColor clearColor];
    return header;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((kScreenWidth-35)/2,80);
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(kScreenWidth,80);
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.collectionViewModelArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ListCollectionViewCell  *cell = (ListCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"MainCellName" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.layer.cornerRadius = 6;
    cell.layer.masksToBounds = YES;
    cell.list = self.collectionViewModelArray[indexPath.row];
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    FBDevicesList *list = self.collectionViewModelArray[indexPath.row];
    if (list.role == EQUESCAT) {
        
        CatVideoVController *video = [[CatVideoVController alloc]init];
        video.hidesBottomBarWhenPushed = YES;
        video.bid = list.bid;
        [self.navigationController pushViewController:video animated:YES];
        
    }else{
        
         YKVL0MainViewController *vc = [[YKVL0MainViewController alloc]init];
         vc.hidesBottomBarWhenPushed = YES;
         vc.bid = list.bid;
        [self.navigationController pushViewController:vc animated:YES];
    }
     
    
}



- (UIImageView*)backgroundImageView
{
    if (!_backgroundImageView) {
         _backgroundImageView = [[UIImageView alloc]init];
        [self.view addSubview:_backgroundImageView];
        [_backgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
             make.left.equalTo(self.view.mas_left);
             make.right.equalTo(self.view.mas_right);
             make.top.equalTo(self.view.mas_top);
             make.bottom.equalTo(self.view.mas_bottom);
        }];
    }
    return _backgroundImageView;
}




#pragma mark 打开蓝牙搜索设备

- (void)no_devices_start_search_blu
{

    if(!self.espFBYBleHelper){
        
        
        [self start_blu];
        
        // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
        __block int timeout = 30; // 倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _blu_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_blu_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_blu_timer, ^{
            
            timeout--;
            
            NSLog(@"devices start search blu time --%d",timeout);
            if (timeout <= 0) {
                        
                dispatch_async(dispatch_get_main_queue(), ^{
                
                    if(_blu_timer){
                       dispatch_source_cancel(_blu_timer);
                        _blu_timer = nil;
                    }
                    
                    [self.espFBYBleHelper stopScan];
                     self.espFBYBleHelper = nil;
                });
            }
            
        });
        dispatch_resume(_blu_timer);
    }

}



- (void)start_blu
{
    __weak DevicesViewController *weakSelf = self;
    self.espFBYBleHelper = [ESPFBYBLEHelper share];
    self.espFBYBleHelper.bleScanSuccessBlockStatus = ^(CBManagerState status) {
   
        NSLog(@"status-->%ld",(long)status);
        if (status == CBManagerStatePoweredOn) {
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                if (weakSelf.alertController) {
                    [weakSelf.alertController dismissViewControllerAnimated:YES completion:nil];
                }
                
                //[SVProgressHUD showWithStatus:NSLocalizedString(@"Scanning WiFi", nil)];
            }];
        }else if(status == CBManagerStateUnauthorized){
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                if (weakSelf.alertController) {
                   [weakSelf.alertController dismissViewControllerAnimated:YES completion:nil];
                }
                weakSelf.alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Note", nil) message:NSLocalizedString(@"The mobile phone Bluetooth is not turned on. Please go to the system settings to turn on Bluetooth or click the Bluetooth option to allow a new connection", nil) preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"set", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weakSelf.navigationController popViewControllerAnimated:YES];
                    
                      NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    [[UIApplication sharedApplication] openURL:url];
                    
                    
                }];
                [weakSelf.alertController addAction:deleteButton];
                [weakSelf presentViewController:weakSelf.alertController animated:YES completion:nil];
            }];
        }else if(status == CBManagerStatePoweredOff){
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                if (weakSelf.alertController) {
                   [weakSelf.alertController dismissViewControllerAnimated:YES completion:nil];
                }
                weakSelf.alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Note", nil) message:NSLocalizedString(@"The Bluetooth function of your phone is not turned on. Please turn on the Bluetooth function of your phone.", nil) preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
                }];
                [weakSelf.alertController addAction:deleteButton];
                [weakSelf presentViewController:weakSelf.alertController animated:YES completion:nil];
            }];
        }
    };

    self.filterContent = [ESPDataConversion loadBlufiScanFilter];
   
   //开始扫描设备
   [self scanDeviceInfo];
    
}

- (void)scanDeviceInfo {
     NSLog(@"start search blu devices \n");
    [self.espFBYBleHelper startScan:^(ESPPeripheral * _Nonnull device) {
        // NSLog(@"blu search device.uuid-->%@ device.name--->%@ \n",device.uuid,device.name);
        if ([self shouldAddToSource:device] && ([device.name containsString:@"VL2"] || [device.name containsString:@"VL4"] || [device.name containsString:@"CAT"])){
            [self.espFBYBleHelper stopScan];
             self.espFBYBleHelper = nil;
             self.search_device = device;
             if(_blu_timer){
               dispatch_source_cancel(_blu_timer);
               _blu_timer = nil;
             }
            NSLog(@"device.uuid-->%@ \n",device.uuid);
            NSLog(@"device.name-->%@ \n",device.name);
       
            dispatch_async(dispatch_get_main_queue(), ^{
        
                BluSearchVController *blu_service = [[BluSearchVController alloc] initWithType:kWHCustomAnimationTypePush];
                blu_service.addClickBlock = ^(UIButton * _Nonnull sender) {
                     self.tabBarController.tabBar.hidden = YES;
                    [self showWifi];
                };
                blu_service.is_cat = [device.name containsString:@"CAT"];
                blu_service.dismissClickBlock = ^(UIButton * _Nonnull sender){
                    self.tabBarController.tabBar.hidden = NO;
                };
                blu_service.definesPresentationContext = YES;
                blu_service.view.backgroundColor   = [UIColor colorWithRed:0 green:0 blue:0 alpha:.4];
                blu_service.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                self.tabBarController.tabBar.hidden = YES;
               [self presentViewController:blu_service animated:YES completion:nil];
                
            });
        
        }
    }];
}


- (BOOL)shouldAddToSource:(ESPPeripheral *)device {
    // Check filter
    if (_filterContent && _filterContent.length > 0) {
        if (!device.name || ![device.name hasPrefix:_filterContent]) {
            // The device name has no filter prefix
            return NO;
        }
    }
    return YES;
}



- (void)showWifi
{
    NSLog(@"搜到设备去添加");
    
//    if(self.search_device){
    
        VL4BLUViewController *vc = [[VL4BLUViewController alloc]init];
        vc.devicetype = [self.search_device.name containsString:@"VL2"] ? EQUESVL2 : EQUESVL4;
        vc.is_Search = YES;
        vc.bind_way = 1;
        vc.send_ip = YES;
       [vc connect:self.search_device];
       [self.navigationController pushViewController:vc animated:YES];
    
//    }
}

- (void)remove_blu
{
    if(_blu_timer){
       dispatch_source_cancel(_blu_timer);
        _blu_timer = nil;
    }
    
    if(_espFBYBleHelper){
       [self.espFBYBleHelper stopScan];
        self.espFBYBleHelper = nil;
    }
    
}


@end
